
/**
 * mouseWheelFlag
 * @param event window.event
 * @returns up | down
 */
export const mouseWheelFlag: (event: any) => string = (event: any) => {
  let delta = 0
  if (!event) event = window.event
  if (event.wheelDelta) {
    //IE、chrome浏览器使用的是wheelDelta，并且值为“正负120”
    delta = event.wheelDelta / 120
    if ((window as any).opera) delta = -delta //因为IE、chrome等向下滚动是负值，FF是正值，为了处理一致性，在此取反处理
  } else if (event.detail) {
    //FF浏览器使用的是detail,其值为“正负3”
    delta = -event.detail / 3
  }
  return delta > 0 ? 'up' : 'down'
}

/**
 * debounce 防抖
 * @param func 须要包装的函数
 * @param delay 延迟时间，单位ms
 * @param immediate 是否默认执行一次(第一次不延迟)
 */
export const debounce
  : (func: any, delay: number, immediate?: boolean) => any
  = (func, delay = 100, immediate = false) => {
    let timer: number | any
    return (...args: any) => {
      if (immediate) {
        func.apply(this, args) // 确保引用函数的指向正确，而且函数的参数也不变
        immediate = false
        return
      }
      clearTimeout(timer)
      timer = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
  }

/**
 * throttle 节流
 * @param func 须要包装的函数
 * @param delay 延迟时间，单位ms
 */
export const throttle
  : (func: any, delay: number, immediate?: boolean) => any
  = (func, delay = 100) => {
    let flag = false;
    return (...args: any) => {
      if (!flag) {
        flag = true;
        setTimeout(() => {
          flag = false;
          func.call(this, ...args);
        }, delay);
      }
    }
  }
